import { ModalForm, ProFormText } from '@ant-design/pro-form';
import React, { useImperativeHandle, forwardRef, useState, useRef, useEffect } from 'react';
import { message, Form, Tree } from 'antd';
import request from '@/utils/request';
import apiPath from '@/utils/apiPath.js';

const EditModalFormRef = (props, ref) => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState({});
  const [authTreeData, setAuthTreeData] = useState([]);
  const [authCheckedKeys, setAuthCheckedKeys] = useState([]);
  const modalformRef = useRef();
  
  useImperativeHandle(ref, () => ({
    initModal: (row) => {
      if (row.id) {
        modalformRef.current?.setFieldsValue(row);
      } else {
        modalformRef.current?.resetFields();
      }
      getAuthTree();
      setCurrentRow(row);
      handleModalVisible(true);
    }
  }))

  /**
   * 添加节点
   *
   * @param fields
   */
  const handleAdd = async (fields) => {
    let method = 'POST';
    let url = apiPath.ADMIN_ROLE_HANDLE;
    let tips = '';
    let submitForm = {
      name: fields.name,
      auths: authCheckedKeys
    };
    if (currentRow.id) {
      url = `${url}/${currentRow.id}`;
      method = 'PUT';
      tips = '修改';
    } else {
      tips = '新建';
    }
    const hide = message.loading(`正在${tips}`);
    try {
      await request(url, {
        method,
        data: submitForm,
      });
      hide();
      props.onReload();
      message.success(`${tips}成功`);
      return true;
    } catch (error) {
      console.error(error);
      hide();
      message.error(`${tips}失败请重试`);
      return false;
    }
  };

  const sonsTree = (arr) => {
    arr = _.map(arr, (item) => {
      return {
        key: item.id,
        title: item.name,
        action_key: item.action_key,
        type: item.type,
        pid: item.pid,
      }
    });
    let topItem = {
      key: 0,
      title: '',
      children: []
    };
    let _forFn = (arr, pItem) => {
        pItem.children = pItem.children ? pItem.children : [];
        for (let i = 0; i < arr.length; i++) {
            let item = _.pick(arr[i], 'key', 'title', 'action_key', 'type', 'pid');
            if (item.pid == pItem.key) {
                pItem.children.push(item);
                _forFn(arr, item);
            }
        }
    };
    _forFn(arr, topItem);
    return topItem.children;
  }

  const getAuthTree = async () => {
    const res = await request(apiPath.ADMIN_AUTH_HANDLE, {
      method: 'GET',
      params: {
        page: 1,
        per_page: 1000
      },
    });
    const treeData = sonsTree(_.cloneDeep(res.data.list), 0);
    setAuthTreeData(treeData);
  }

  useEffect(async () => {
    if (currentRow.id) {
      const tmpArr = [];
      _.map(currentRow.auths, (item) => {
        tmpArr.push(item.id);
      });
      setAuthCheckedKeys(tmpArr);
      modalformRef?.current.setFieldsValue({
        auths: tmpArr
      });
    } else {
      setAuthCheckedKeys([]);
    }
  }, [currentRow.id]);

  return (
    <ModalForm
      title={`设置权限`}
      width="400px"
      formRef={modalformRef}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      visible={createModalVisible}
      onVisibleChange={(value) => {
        handleModalVisible(value);
      }}
      onFinish={async (value) => {
        const success = await handleAdd(value);

        if (success) {
          handleModalVisible(false);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      }}
    >
      <ProFormText
        rules={[
          {
            required: true,
            message: "角色名为必填项",
          },
        ]}
        width="md"
        label="角色名"
        name="name"
      />
      {
        authTreeData.length &&
        <Form.Item
          rules={[
            {
              required: true,
              message: "请配置权限点",
            },
          ]}
          width="md"
          label="权限点"
          name="auths">
          <Tree
            checkable
            defaultExpandAll={true}
            checkStrictly
            checkedKeys={authCheckedKeys}
            onCheck={({ checked }) => {
              modalformRef?.current.setFieldsValue({
                auths: checked
              });
              setAuthCheckedKeys(checked);
            }}
            treeData={authTreeData}
          />
        </Form.Item>
      }
    </ModalForm>
  )
}
const EditModalForm = forwardRef(EditModalFormRef);
export default EditModalForm;